import os
from ament_index_python.packages import get_package_share_directory

from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, SetEnvironmentVariable, IncludeLaunchDescription
from launch.substitutions import Command, LaunchConfiguration

from launch_ros.actions import Node
from launch_ros.parameter_descriptions import ParameterValue
from ament_index_python.packages import get_package_prefix, get_package_share_directory
from launch.launch_description_sources import PythonLaunchDescriptionSource

def generate_launch_description():

    model_arg = DeclareLaunchArgument(name="model", default_value=os.path.join(
        get_package_share_directory("arduinobot_description"), "urdf", "arduinobot.urdf.xacro"),
        description="Absolute path to robot urdf file"
    )
    # 通过xacro命令将xacro文件转换为urdf文件
    # 这里使用了ParameterValue来将xacro文件的内容传递给robot_description参数
    robot_description = ParameterValue(Command(["xacro ", LaunchConfiguration("model")])
                                       , value_type=str)
    
    robot_state_publisher_node = Node(
        package="robot_state_publisher",
        executable="robot_state_publisher",
        parameters=[{"robot_description": robot_description,"use_sim_time": True}]
    )

    env_var = SetEnvironmentVariable("GAZEBO_MODEL_PATH", os.path.join(
        get_package_prefix("arduinobot_description"), "share"))

    start_gazebo_server = IncludeLaunchDescription(
        PythonLaunchDescriptionSource(os.path.join(
            get_package_share_directory("gazebo_ros"), "launch", "gzserver.launch.py"))
    )
    start_gazebo_client = IncludeLaunchDescription(
        PythonLaunchDescriptionSource(os.path.join(
            get_package_share_directory("gazebo_ros"), "launch", "gzclient.launch.py"))
    )
    spawn_robot = Node(
        package="gazebo_ros",
        executable="spawn_entity.py",
        arguments=[
            "-entity", "arduinobot",
            "-topic", "robot_description",
        ]
    )

    return LaunchDescription([
        env_var,
        model_arg,
        robot_state_publisher_node,
        start_gazebo_server,
        start_gazebo_client,
        spawn_robot
    ])

